package com.njtoyo.taxi.admin.rest.controller.business.ride;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import cn.hutool.poi.excel.StyleSet;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.njtoyo.taxi.admin.aop.PermissionScope;
import com.njtoyo.taxi.admin.rest.presenter.business.ride.RideListPresenter;
import com.njtoyo.taxi.admin.rest.presenter.business.ride.scan_ride.ScanRideDetailsPresenter;
import com.njtoyo.taxi.admin.rest.presenter.business.ride.scan_ride.ScanRideListPresenter;
import com.njtoyo.taxi.admin.rest.wrapper.business.ride.RideQueryWrapper;
import com.njtoyo.taxi.admin.rest.wrapper.business.ride.ScanRideWrapper;
import com.njtoyo.taxi.admin.service.business.ride.ScanRideOrderService;
import com.taxi.entity.common.RestResult;
import com.njtoyo.taxi.entity.backend.AdminUser;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.ss.usermodel.CellStyle;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@Api(value = "行程管理", tags = {"行程管理"})
@RequestMapping("business/scan-ride")
public class ScanRideController {
    @Autowired
    private ScanRideOrderService sweepOrderService;

    @GetMapping("")
    @ApiOperation(value = "扫码订单列表", notes = "扫码订单列表,权限:ride_scan_list")
    @PermissionScope(names = {"ride_scan_list"})
    RestResult<Page<ScanRideListPresenter>> sweepOrderList(@ApiIgnore @ModelAttribute("admin") AdminUser adminUser,
                                                           @Valid ScanRideWrapper wrapper) {
        return sweepOrderService.sweepOrderList(adminUser, wrapper);
    }


    @GetMapping("/export")
    @ApiOperation(value = "行程列表-导出")
    void rideListExport(@ApiIgnore @ModelAttribute("admin") AdminUser adminUser, @Valid ScanRideWrapper wrapper, HttpServletResponse response) throws IOException {
        wrapper.setSize(100000);
        RestResult<Page<ScanRideListPresenter>> result = sweepOrderService.sweepOrderList(adminUser, wrapper);
        Page<ScanRideListPresenter> page = result.getData();
        List<Map<String, Object>> rows = new ArrayList<>();
        if (CollUtil.isNotEmpty(page.getRecords())) {
            for (ScanRideListPresenter ride : page.getRecords()) {
                Map<String, Object> row = new HashMap<>();
                row.put("ID", ride.getId());
                row.put("用户信息", StrUtil.format("{}/{}/{}", ride.getCustomerId(), ride.getCustomerName(), ride.getCustomerMobileNumber()));
                row.put("位置信息", "");
                row.put("司机接单信息", "司机ID:" + ride.getDriverId() + "\n " +
                        "姓名:" + ride.getDriverName() + "\n" +
                        "手机号:" + ride.getDriverMobileNumber() + "\n" +
                        "所属公司:" + ride.getCompanyName() + "\n" +
                        "车牌号:" + ride.getPlateNumber() + "\n"
                );
                row.put("行政区", ride.getCantonName());
                row.put("扫码时间", ObjectUtil.isNotNull(ride.getCreatedAt()) ? DateUtil.format(ride.getCreatedAt(), DatePattern.NORM_DATETIME_PATTERN) : "");
                row.put("首单立减", ride.getIsDiscountable() ? "是" : "否");
                row.put("是否完成行程", ride.getIsFinished() ? "是" : "否");
                row.put("支付信息", "金额:" + ride.getAmount() + "\n " +
                        "支付方式:" + ride.getPaymentChannel().getDesc() + "\n" +
                        "支付结果:" + (ride.getIsPaid() ? "已支付" : "未支付") + "\n"
                );
                row.put("支付金额", ObjectUtil.isNotNull(ride.getAmount()) ? ride.getAmount() : "");
                rows.add(row);
            }
        } else {
            Map<String, Object> row = new HashMap<>();
            row.put("ID", "");
            row.put("用户信息", "");
            row.put("位置信息", "");
            row.put("司机接单信息", "");
            row.put("行政区", "");
            row.put("扫码时间", "");
            row.put("首单立减", "");
            row.put("是否完成行程", "");
            row.put("支付信息", "");
            rows.add(row);
        }
        ExcelWriter writer = ExcelUtil.getWriter();
        StyleSet style = writer.getStyleSet();
        CellStyle cellStyle = style.getHeadCellStyle();
        cellStyle.setWrapText(true);
        writer.write(rows, true);
        response.setContentType("application/vnd.ms-excel;charset=utf-8");
        response.setHeader("Content-Disposition", "attachment;filename=ride_order.xls");
        ServletOutputStream out = response.getOutputStream();

        writer.flush(out, true);
        writer.close();
        IoUtil.close(out);
    }

    @GetMapping("/{id}")
    @ApiOperation(value = "扫码订单详情", notes = "扫码订单详情,权限:ride_scan_detail")
    @PermissionScope(names = {"ride_scan_detail"})
    RestResult<ScanRideDetailsPresenter> sweepOrderDetails(@PathVariable("id") Long id) {
        return sweepOrderService.sweepOrderDetails(id);
    }


}
